package org.uugu.counter.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import org.uugu.counter.R;
import org.uugu.counter.Support.CommonParam;
import org.uugu.counter.Support.DatabaseUtils;
import org.uugu.counter.Support.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据输入Activity
 * Created by Silence on 2014/3/28.
 */
public class WorkActivity extends Activity {

    // 添加数据按钮
    private Button button;

    // 开始统计按钮
    private Button workBtn;

    // DB连接
    private DatabaseUtils dbUtils;

    // 数据展示
    private GridView gv;

    // GroupID
    private int id;

    // 单挑数据ID
    private int dataId;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.work);
        TextView groupName = (TextView)findViewById(R.id.groupNameTitle);
        Intent intent =getIntent();
        groupName.setText("以下是【"+intent.getStringExtra("groupName")+"】组数据：");
        // 实例化DBUtils
        dbUtils = new DatabaseUtils(this, CommonParam.DB_NAME, CommonParam.VERSION);
        id = intent.getIntExtra("id", 0);
        Toast toast = Toast.makeText(WorkActivity.this, "已打开该组数据，组号："+id, Toast.LENGTH_SHORT);
        toast.show();
        button = (Button)findViewById(R.id.inputBtn);
        workBtn = (Button)findViewById(R.id.startCountBtn);
        gv = (GridView)findViewById(R.id.workGridView);
        gv.setOnItemClickListener(new GridViewItemClickListener());
        button.setOnClickListener(new ButtonListener());
        workBtn.setOnClickListener(new WorkBtnListener());
        freshGridView();
    }

    /**
     * 刷新页面数据
     */
    public void freshGridView(){
        Cursor cursor = dbUtils.getReadableDatabase().rawQuery("select * from data where group_id = ?", new String[]{String.valueOf(id)});
        List<Map<String, String>> searchResult = dbUtils.converCursorToList(cursor);
        SimpleAdapter sa = new SimpleAdapter(this, searchResult, R.layout.workcell,
                new String[]{"id", "width", "w_num", "hight", "h_num"},
                new int[]{R.id.textView, R.id.textView2, R.id.textView3, R.id.textView4, R.id.textView5});
        gv.setAdapter(sa);
    }

    // 填写数据按钮监听事件
    class ButtonListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {

            final LinearLayout inputForm = (LinearLayout)getLayoutInflater().inflate(R.layout.inputform, null);
            new AlertDialog.Builder(v.getContext()).setTitle("填写数据")
                   .setView(inputForm)
                    .setPositiveButton("添加", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            EditText width = (EditText)inputForm.findViewById(R.id.width);
                            EditText wNum = (EditText)inputForm.findViewById(R.id.wNum);
                            EditText hight = (EditText)inputForm.findViewById(R.id.hight);
                            EditText hNum = (EditText)inputForm.findViewById(R.id.hNum);

                            int widthInt = StringUtils.Str2Int(width.getText().toString());
                            int wNumInt = StringUtils.Str2Int(wNum.getText().toString());
                            int hightInt = StringUtils.Str2Int(hight.getText().toString());
                            int hNumInt = StringUtils.Str2Int(hNum.getText().toString());

                            ContentValues values = new ContentValues();
                            values.put("width", widthInt);
                            values.put("w_num", wNumInt);
                            values.put("hight", hightInt);
                            values.put("h_num", hNumInt);
                            values.put("group_id", id);

                            dbUtils.getWritableDatabase().insert("data", null, values);
                            freshGridView();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).create().show();
        }
    }

    // 开始统计监听事件
    class WorkBtnListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            Bundle data = new Bundle();
            Intent intent = new Intent(WorkActivity.this, ResultActivity.class);
            data.putInt("groupId", id);
            intent.putExtras(data);

            startActivity(intent);

        }
    }

    class GridViewItemClickListener implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            HashMap<String, Object> item=(HashMap<String, Object>) parent.getItemAtPosition(position);
            AlertDialog.Builder builder = new AlertDialog.Builder(WorkActivity.this).setTitle("确认删除")
                    .setMessage("确认删除ID为" + item.get("id") + "的该行数据吗？");
            dataId = Integer.valueOf(item.get("id").toString());
            setPositiveButton(builder);
            setNegativeButton(builder).create().show();
        }

        private AlertDialog.Builder setPositiveButton(AlertDialog.Builder builder){
            return builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dbUtils.getWritableDatabase().delete("data", "id = ?", new String[]{String.valueOf(dataId)});
                    Toast toast = Toast.makeText(WorkActivity.this, "已删除该组数据，组号："+dataId, Toast.LENGTH_SHORT);
                    toast.show();
                    // 刷新页面数据
                    freshGridView();
                }
            });
        }

        private AlertDialog.Builder setNegativeButton(AlertDialog.Builder builder){
            return builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
        }
    }

}